package com.example.fengyungo.controller.admin;


import com.example.fengyungo.constant.AdminConstant;
import com.example.fengyungo.domain.dto.AdminAddDTO;
import com.example.fengyungo.domain.dto.AdminLoginDTO;
import com.example.fengyungo.domain.pojo.Admin;
import com.example.fengyungo.exception.NotLoginException;
import com.example.fengyungo.result.Result;
import com.example.fengyungo.service.AdminService;
import com.example.fengyungo.service.LoginService;
import com.example.fengyungo.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "风运Go管理端")
@RestController
@RequestMapping("/admin/admin")
public class AdminController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation("测试")
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("555");
        // return Result.success("当前管理员id：" + adminService.test());
    }

    @ApiOperation("测试异常")
    @GetMapping("/exception/{test}")
    public Result<String> testException(@PathVariable String test) {
        if (test.equals("1")) {
            throw new NotLoginException("未登录");
        }
        return Result.success();
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@RequestBody AdminLoginDTO admin) {
        String username = admin.getAdminUsername();
        String password = admin.getAdminPassword();
        return loginService.login(username, password);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public Result logout() {
        return loginService.logout();
    }

    @ApiOperation("添加管理员")
    @PostMapping("/add")
    public Result addAdmin(@RequestBody AdminAddDTO adminAddDTO) {
        Admin admin = new Admin();
        // 属性拷贝
        BeanUtils.copyProperties(adminAddDTO, admin);

        Boolean res = adminService.addAdmin(admin);
        if (!res) {
            return Result.error(AdminConstant.ADD_FAIL);
        }
        return Result.success();
    }

    @ApiOperation("修改管理员")
    @PutMapping("/update")
    public Result updateAdmin(@RequestBody Admin admin) {
        Integer res = adminService.updateAdmin(admin);
        if (res == 0) {
            return Result.error(AdminConstant.UPDATE_FAIL);
        }
        return Result.success();
    }
}
